#include "log.hpp"
volatile bool quit = false;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Usage\n\t" << argv[0] << " ip port" << endl;
        exit(USAGE_ERR);
    }
    string ip = argv[1];
    uint16_t port = atoi(argv[2]);

    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        logMessage(FATAL, "sockfd :%s", strerror(errno));
        exit(SOCKET_ERR);
    }
    // 2.发起连接请求
    // 2.1填充服务器基本信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    inet_aton(ip.c_str(), &server.sin_addr);
    // 2.2发起请求
    if (connect(sockfd, (const struct sockaddr *)&server, sizeof server) != 0)
    {
        logMessage(FATAL, "connect :%s", strerror(errno));
        exit(CONN_ERR);
    }
    logMessage(DEBUG, "connect :%s,sockfd:%d ", strerror(errno), sockfd);

    string message;
    while (!quit)
    {
        message.clear();
        cout << "请输入你的信息：";
        getline(cin, message);
        if (strcasecmp("quit", message.c_str()) == 0)
            quit = true;

        ssize_t s = write(sockfd, message.c_str(), message.size());
        if (s > 0)
        {
            message.resize(1024);
            ssize_t t = read(sockfd, (void *)message.c_str(), 1024);
            if (t > 0)
            {
                message[t] = '\0';
                cout << "server echo#" << message.c_str() << endl;
            }
        }
        else if (s <= 0)
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}